from django.core.validators import RegexValidator
from django.http.response import JsonResponse
from django.shortcuts import render,HttpResponse,redirect
from utils.tencent.sms import send_sms_single
import random
import json
import redis
from django.conf import settings
from django import forms
from app01 import models
from django.core.exceptions import ValidationError
from utils.tencent.cos import get_credential_dict
# Create your views here.

class LoginModelForm(forms.ModelForm):
    # confirm_password = forms.CharField(label='重置密码',widget=forms.PasswordInput(attrs={'class':
    #     'form-control','placeholder':'重置密码','aria-describedby':"basic-addon1"}))
    password = forms.CharField(
        min_length=4,
        label='密码',
        widget=forms.PasswordInput())

    # confirm_password = forms.CharField(
    #     min_length=4,
    #     label='重复密码',
    #     widget=forms.PasswordInput())
    
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput())
    
    # mobile_phone = forms.CharField(
    #     validators=[RegexValidator(r'^1[3|4|5|6|7|8]\d{9}$','手机号码格式错误'),],
    #     label='手机号码',
    #     widget=forms.TextInput()
    # ) 
    
    class Meta:
        model=models.UserInfo
        fields=['username','password']
    def __init__(self,*args, **kwargs):
        super().__init__(*args, **kwargs)
        # super(RegisterModelForm,self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class']='form-control'
            field.widget.attrs['placeholder']='请输入%s'%field.label
            # field.widget.attrs['aria-describedby']='basic-addon1'
            field.widget.attrs['autocomplete']='new-password'   # forbidden browser autocomplete
            # field.label=name

    # def clean(self):
    #     # print('clean:',self.cleaned_data)
    #     # if both password exist:
    #     if ('confirm_password' in self.cleaned_data.keys() and \
    #         'password' in self.cleaned_data.keys()):
    #         if self.cleaned_data['confirm_password']!=self.cleaned_data['password']:
    #             raise ValidationError('二次输入密码不一致',code='required') 
    #     return self.cleaned_data
    # def clean_username(self):
    #     user_existed = models.UserInfo.objects.filter(username=self.cleaned_data['username']).first()
    #     if user_existed:
    #         raise ValidationError("用户名已存在", code='required')
    #     return self.cleaned_data['username']


class RegisterModelForm(LoginModelForm):
    # confirm_password = forms.CharField(label='重置密码',widget=forms.PasswordInput(attrs={'class':
    #     'form-control','placeholder':'重置密码','aria-describedby':"basic-addon1"}))
    # password = forms.CharField(
    #     min_length=4,
    #     label='密码',
    #     widget=forms.PasswordInput())

    confirm_password = forms.CharField(
        min_length=4,
        label='重复密码',
        widget=forms.PasswordInput())
    
    # code = forms.CharField(
    #     label='验证码',
    #     widget=forms.TextInput())
    
    # mobile_phone = forms.CharField(
    #     validators=[RegexValidator(r'^1[3|4|5|6|7|8]\d{9}$','手机号码格式错误'),],
    #     label='手机号码',
    #     widget=forms.TextInput()
    # ) 
    
    class Meta:
        model=models.UserInfo
        fields=['username', 'email', 'password', 'confirm_password', 'mobile_phone']
    def __init__(self,*args, **kwargs):
        # super().__init__(*args, **kwargs)
        super(RegisterModelForm,self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class']='form-control'
            field.widget.attrs['placeholder']='请输入%s'%field.label
            # field.widget.attrs['aria-describedby']='basic-addon1'
            field.widget.attrs['autocomplete']='new-password'   # forbidden browser autocomplete
            # field.label=name

    def clean(self):
        # print('clean:',self.cleaned_data)
        # if both password exist:
        if ('confirm_password' in self.cleaned_data.keys() and \
            'password' in self.cleaned_data.keys()):
            if self.cleaned_data['confirm_password']!=self.cleaned_data['password']:
                raise ValidationError('二次输入密码不一致',code='required') 
        return self.cleaned_data
    def clean_username(self):
        user_existed = models.UserInfo.objects.filter(username=self.cleaned_data['username']).first()
        if user_existed:
            raise ValidationError("用户名已存在", code='required')
        return self.cleaned_data['username']
        
def register(request):
    if request.method=='GET':
        objs = RegisterModelForm()
        return render(request,'app01/register.html',{'objs':objs})
    else:
        objs = RegisterModelForm(request.POST)
        ret = {'status':True,'msg':''}
        if objs.is_valid():
            print(objs.cleaned_data)
            ret['status']=True
            # user_existed = models.UserInfo.objects.filter(username=objs.cleaned_data['username']).first()
            # if not user_existed:
            objs.save()
                
            return render(request,'app01/register.html', {'objs':objs,'ret':ret})
        else:
            ret['status']=False
            import json
            ret['msg'] = objs.errors
            v = json.dumps(ret)
            return HttpResponse(v)
            # return render(request,'app01/register.html', {'objs':objs,'ret':ret})

def send_sms(request):
    
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse("模板错误")
    code=random.randrange(1000,9999)
    res = send_sms_single('12811118888', template_id, [code,])
    print(res)
    if res['result']==0:
        return HttpResponse("send_sms发送成功")
    else:
        return HttpResponse(res['errmsg'])

def send_sms_code(tpl, mobile_phone):
    ret = {'status':False, 'msg':''}
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)

    if not template_id:
        ret['msg'] = '模板错误'
    
    code=random.randrange(1000,9999)
    res = send_sms_single(mobile_phone, template_id, [code,])
    print(res)
    if res['result']==0:
        ret={'status':True, 'msg':'send_sms_code发送成功'}
    else:
        ret={'status':False, 'msg':res['errmsg']}
    return ret 
def set_redis(value, ex):
    conn = redis.Redis(host='127.0.0.1',port=6379,password='abc',encoding='utf-8')
    conn.set('111',9999, ex=ex)
    value = conn.get('111')


def submit_code(request):
    if request.method=="GET":
        pass
    else:
        objs = RegisterModelForm(request.POST)
        objs.is_valid()
        ret = {'status':True, 'msg':''}
        if 'mobile_phone' in objs.cleaned_data.keys():
            mobile_phone=objs.cleaned_data['mobile_phone']
            # TODO
            # GET code by SMS
            # ret = send_sms_code('register',mobile_phone) 
            v = json.dumps(ret)
            return HttpResponse(v)

        else:
            ret['status']=False
            import json
            
            ret['msg'] = {'mobile_phone':objs.errors['mobile_phone']}
            v = json.dumps(ret)
            return HttpResponse(v)

def index(request):
    
    return render(request,"app01/index.html")  


def login(request):
    if request.method=='GET':
        objs = LoginModelForm()
        return render(request,"app01/login.html",{'objs':objs})      
    else:
        objs = LoginModelForm(request.POST)
        ret = {'status':False,'msg':''}
        print(objs)
        if objs.is_valid():
            print(objs.cleaned_data)
            ret['status']=True
            username = objs.cleaned_data['username']
            password = objs.cleaned_data['password']
            existed = models.UserInfo.objects.filter(username=username, password=password).first()
            if existed:
                print('redirect')
                ret['status']=True
                import json
                v = json.dumps(ret)
                return HttpResponse(v)
                # return render(request, 'app01/login.html',{'ret':ret})
            # user_existed = models.UserInfo.objects.filter(username=objs.cleaned_data['username']).first()
            # if not user_existed:
            # objs.save()
                
            return render(request,'app01/register.html', {'objs':objs,'ret':ret})
        else:
            ret['status']=False
            import json
            ret['msg'] = objs.errors
            v = json.dumps(ret)
            return HttpResponse(v)
            # return render(request,'app01/register.html', {'objs':objs,'ret':ret})
def upload_file(request):
    return render(request, 'app01/upload_file.html')
def demo2(request):
    return render(request, 'app01/cos_credential.html')
# def get_credential(request):
#     print('run get credential')
    
#     return JsonResponse({})

def cos_credential(request):
    bucket = "xiao-1253629186"
    region = 'ap-beijing'
    result_dict = get_credential_dict(bucket,region)
    print('views/cos_credential:',result_dict)
    return JsonResponse(result_dict)
